package br.uniriotec.ppgi.leo.controller.run;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.log4j.Logger;

public class SystemCaller {
	
	private static Logger logger = Logger.getLogger(SystemCaller.class);
	
	public static void callSystemProccess(String command) throws IOException{
		
		String[] args = command.split(" ");
		
		if (args.length <= 0) {
			logger.error("Need command to run");
			System.exit(-1);
		}

		if (args.length == 0) {
            logger.error("You must supply at least one argument.");
            return;
        }
 
        ProcessBuilder processBuilder = new ProcessBuilder(args);
        processBuilder.redirectErrorStream(true);
 
        Process process = processBuilder.start();
        copy(process.getInputStream(), System.out);
        try {
			process.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        
        logger.info("Exit Status : " + process.exitValue());
		
		
	}
	
	private static void copy(InputStream in, OutputStream out) throws IOException {
        while (true) {
            int c = in.read();
            if (c == -1) {
                break;
            }
            out.write((char) c);
        }
    }
}
